package com.huo.http;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.huo.common.StringUtil;

/**
 * <p>Description: Http协议服务类</p>
 * @author Huoyan
 * @version 1.0
 * <p>Copyright 2011</p>
 */

public class HttpService {
	
	private static final Log log = LogFactory.getLog(HttpService.class);
	
	private String refer = "";
	private String charset = "GB2312,utf-8;q=0.7,*;q=0.7";
	private String language = "zh-cn,zh;q=0.5";
	private String userAgent = "Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0";
	private String contentType = "application/x-www-form-urlencoded;charset=UTF-8";
	
	private DefaultHttpClient client = new DefaultHttpClient();
	
	public HttpService(){
		//initClient();
	}
	
	protected void initClient(){
		//The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents
		HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
	}
	
	/**
	 * 发送get请求
	 * @param uri
	 * @return String 响应结果
	 */
	public String getReturnStr(String uri){
		String s = null;
		try {
			s = EntityUtils.toString(get(uri, null).getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	/**
	 * 发送get请求
	 * @param uri
	 * @param client
	 * @param cookies
	 * @return
	 */
	public String getReturnStr(String uri, String cookies){
		String s = null;
		try {
			s = EntityUtils.toString(get(uri, cookies).getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	public HttpResponse get(String uri){
		HttpResponse res = null;
		try {
			res = get(uri, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	/**
	 * 发送get请求
	 * @param uri
	 * @param client
	 * @param cookies
	 * @return
	 */
	public HttpResponse get(String uri, String cookies){
		HttpResponse res = null;
		HttpGet req = new HttpGet(uri);
		try {
			//设置头部
			setHeaders(req, "get", cookies);
			res = client.execute(req);
		} catch (Exception e) {
			log.error("发送get请求时错误，uri: " + uri + "错误信息: " + e.getMessage());
		}
		return res;
	}
	
	/**
	 * 发送post请求
	 * @param uri
	 * @param l
	 * @param client
	 * @return
	 */
	public String postReturnStr(String uri, List<NameValuePair> l){
		String s = null;
		try {
			s = EntityUtils.toString( post(uri, l , null).getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	/**
	 * 发送post请求
	 * @param uri
	 * @param se
	 * @param client
	 * @return
	 */
	public String postReturnStr(String uri, String se){
		String s = null;
		try {
			s = EntityUtils.toString(post(uri, null, new StringEntity(se, HTTP.UTF_8)).getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	/**
	 * 发送post请求
	 * @param uri
	 * @param l
	 * @param se
	 * @param client
	 * @return
	 */
	private HttpResponse post(String uri, List<NameValuePair> l,
			StringEntity se) {
		return post(uri, l, se, null);
	}

	/**
	 * 发送post请求
	 * @param uri
	 * @param l
	 * @param se
	 * @param client
	 * @param cookies
	 * @return
	 */
	public HttpResponse post(String uri, List<NameValuePair> l,
			StringEntity se, String cookies) {
		HttpResponse res = null;
		HttpPost req = new HttpPost(uri);
		try {
			// 设置请求头
			setHeaders(req, "post", cookies);
			// 设置提交参数
			if (l != null) {
				req.setEntity(new UrlEncodedFormEntity(l, HTTP.UTF_8));
			} else if (se != null) {
				req.setEntity(se);
			}
			res = client.execute(req);
		} catch (Exception e) {
			log.error("发送post请求时错误, uri: " + uri + "错误信息: " + e.getMessage());
		}
		return res;
	}
	
	/**
	 * 获取cookie
	 * @param key
	 * @param client
	 * @return
	 */
	public String getCookie(String key){
		String s = null;
		List<Cookie> cookies = client.getCookieStore().getCookies();
		for(Cookie c : cookies){
			if(c.getName().equals(key)){
				s = c.getValue();
				break;
			}
		}
		return s;
	}
	
	/**
	 * 设置cookie
	 * @param client
	 * @param cookies
	 */
	public void setCookie(DefaultHttpClient client, List<Cookie> cookies){
		if(!cookies.isEmpty()){
			for(int i=0;i<cookies.size();i++){
				client.getCookieStore().addCookie(cookies.get(i));
			}
		}
	}
	
	/**
	 * 设置请求头
	 * @param req
	 * @param method
	 */
	protected void setHeaders(HttpRequest req, String method){
		setHeaders(req, method, "");
	}
	
	/**
	 * 设置请求头
	 * @param req
	 * @param method
	 * @param cookie
	 */
	private void setHeaders(HttpRequest req, String method, String cookies){
		//设置请求头
		req.setHeader("Referer", refer);
		if(!StringUtil.isBlank(cookies)){
			//设置cookie
			req.setHeader("Cookie", cookies);
		}
		req.setHeader("Accept-Charset", charset);
		req.setHeader("Accept-Language", language);
		req.setHeader("User-Agent", userAgent);
		req.setHeader("Connection", "keep-alive");
		if("post".equalsIgnoreCase(method)){
			req.setHeader("Content-Type",contentType); //*****************************************************************************必须设置
		}
	}
	
	/**
	 * 关闭http连接
	 */
	public void shutdown(){
		client.getConnectionManager().shutdown();
	}
	
	public String getRefer() {
		return refer;
	}

	public void setRefer(String refer) {
		this.refer = refer;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getUserAgent() {
		return userAgent;
	}

	public void setUserAgent(String userAgent) {
		this.userAgent = userAgent;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public DefaultHttpClient getClient() {
		return client;
	}

	public void setClient(DefaultHttpClient client) {
		this.client = client;
	}

	public static void main(String[] args) {
		
	}

}
